/**
 * Project Name:mauto-web
 * File Name:CORSFilter.java
 * Package Name:com.inftech.mauto.common.filter
 * Date:2016年11月13日下午6:39:25
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.inftech.mauto.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
/**
 * ClassName:CORSFilter <br/>
 * Function: 跨域过滤器. <br/>
 * Date:     2016年11月13日 下午6:39:25 <br/>
 * @author   jeno
 * @version  
 * @since    JDK 1.7
 */
public class CORSFilter implements Filter {

	private final Logger LOG = Logger.getLogger(this.getClass());
	
	private FilterConfig config = null;
	
	@Override
	public void destroy() {
		
		this.config = null;
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) arg1;
		HttpServletRequest httpRequest = (HttpServletRequest) arg0;
        // 表明它允许"http://xxx"发起跨域请求
        httpResponse.setHeader("Access-Control-Allow-Origin",httpRequest.getHeader("Origin"));
        httpResponse.setHeader("Access-Control-Allow-Credentials","true");   // allow cookie
        // 表明在xxx秒内，不需要再发送预检验请求，可以缓存该结果
        httpResponse.setHeader("Access-Control-Allow-Methods",
                config.getInitParameter("AccessControlAllowMethods"));
        // 表明它允许xxx的外域请求
        httpResponse.setHeader("Access-Control-Max-Age",
                config.getInitParameter("AccessControlMaxAge"));
        // 表明它允许跨域请求包含xxx头
        httpResponse.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		LOG.info("init cors filter start ");
		this.config = arg0;
	}
	

}

